import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_fai_webview/flutter_fai_webview.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:get/get.dart';
import 'package:wakelock/wakelock.dart';

import '../../../bean/bean_integral.dart';
import '../../../bean/bean_train.dart';
import '../../../bean/bean_video.dart';
import '../../../bean/bean_video_course.dart';
import '../../../common/user_helper.dart';
import '../../../utils/log_util.dart';
import '../controller/video_details_code_link_controller.dart';

///  加载 Html 标签
///  嵌入 适配移动端的 默认样式
///  实现 覆盖 Html 页面中的所有的图片添加点击事件
class VideoDetailsCodeLinkPage extends StatefulWidget {
  final VideoModel videoModel;
  final int trainId;
  final TrainBean trainBean;
  final IntegralStatBean integralStatBean;

  const VideoDetailsCodeLinkPage({
    Key key,
    @required this.videoModel,
    this.trainId,
    this.integralStatBean,
    this.trainBean,
  }) : super(key: key);

  @override
  DefaultHtmlBlockDataPageState createState() =>
      DefaultHtmlBlockDataPageState();
}

class DefaultHtmlBlockDataPageState extends State<VideoDetailsCodeLinkPage>
    with WidgetsBindingObserver {
  //原生 发送给 Flutter 的消息
  String message = "--";
  double webViewHeight = 200;
  bool _isFullScreen = false;
  VideoDetailsCodeLinkController _videoDetailsCodeLinkController;

  @override
  void initState() {
    super.initState();
    //使用
    Wakelock.enable();
    _videoDetailsCodeLinkController = Get.put(
        VideoDetailsCodeLinkController(
          widget.videoModel,
          widget.integralStatBean,
          widget.trainId,
          widget.trainBean,
        ),
        tag: widget.videoModel.id.toString());
    _videoDetailsCodeLinkController.closeLoading = false;
    //缓存的人脸识别记录时间
    _videoDetailsCodeLinkController.faceRecognitionNumber =
        UserHelper.getInstance.faceRecognitionNumber;
    Future.delayed(Duration.zero, () {
      _videoDetailsCodeLinkController.initFunction();
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 应用进入前台
      LogUtils.e("App进入 前台");
    } else if (state == AppLifecycleState.paused) {
      // 应用进入后台
      LogUtils.e("应用进入后台");
      _videoDetailsCodeLinkController.stopAllFunction();
      Get.back();
    }
  }

  @override
  Widget build(BuildContext context) {
    num width = MediaQuery.of(context).size.width;
    num height = MediaQuery.of(context).size.height;
    LogUtils.e("width is $width height is  $height");
    return WillPopScope(
      onWillPop: () async {
        _videoDetailsCodeLinkController.closePage();
        return true;
      },
      child: GetBuilder(
        id: 'root',
        tag: widget.videoModel.id.toString(),
        builder: (VideoDetailsCodeLinkController controller) {
          return Scaffold(
            appBar: _isFullScreen
                ? null
                : AppBar(
                    leading: BackButton(
                      onPressed: () {
                        _videoDetailsCodeLinkController.closePage();
                      },
                    ),
                    title: Text("视频详情"),
                  ),
            floatingActionButton: !_isFullScreen
                ? null
                : FloatingActionButton(
                    child: Icon(
                      Icons.exit_to_app,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      _isFullScreen = false;
                      // 强制竖屏
                      SystemChrome.setPreferredOrientations([
                        DeviceOrientation.portraitUp,
                        DeviceOrientation.portraitDown
                      ]);
                      refreshHtmlPage();
                      setState(() {});
                    },
                  ),
            body: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Stack(
                children: [
                  Positioned.fill(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          height: _isFullScreen
                              ? MediaQuery.of(context).size.height
                              : 220,
                          child: FaiWebViewWidget(
                            controller: faiWebViewController,
                            webViewHeight: _isFullScreen
                                ? MediaQuery.of(context).size.height
                                : 220,
                            url: widget.videoModel.videoHtmlUrl,
                            //webview 加载网页链接
                            // htmlBlockData: widget.videoModel.videoUrl,
                            // url: "http://192.168.1.107:7073/learncoal/h5/news/video/details/249.html",
                            //图片添加点击事件
                            htmlImageIsClick: false,
                            //webview 加载信息回调
                            callback: callBack,
                            //图片信息的回调
                            imageCallBack: imageCallBack,
                            //输出日志
                            isLog: true,
                          ),
                        ),
                        buildVideoInfoWidget()
                      ],
                    ),
                  ),
                  buildCloseLoading(controller),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget buildCloseLoading(VideoDetailsCodeLinkController controller) {
    if (!controller.closeLoading) {
      return SizedBox(
        width: 1,
        height: 1,
      );
    }
    return Container(
      color: Colors.white.withOpacity(0.6),
      child: Center(
        child: CupertinoActivityIndicator(),
      ),
    );
  }

  buildVideoInfoWidget() {
    if (_isFullScreen) {
      return SizedBox();
    }
    return Container(
      color: Colors.white,
      width: double.infinity,
      padding: EdgeInsets.all(12),
      margin: EdgeInsets.only(top: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          buildProgressSlider(),
          Container(
            child: Text(
              widget.videoModel.videoName ?? "--",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10),
            child: Text(
              widget.videoModel.videoInfo,
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal),
            ),
          ),
          SizedBox(
            height: 33,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () {
                    if (_isFullScreen) {
                      _isFullScreen = false;
                      // 强制竖屏
                      SystemChrome.setPreferredOrientations([
                        DeviceOrientation.portraitUp,
                        DeviceOrientation.portraitDown
                      ]);
                    } else {
                      _isFullScreen = true;
                      // 强制横屏
                      SystemChrome.setPreferredOrientations([
                        DeviceOrientation.landscapeLeft,
                        DeviceOrientation.landscapeRight
                      ]);
                      refreshHtmlPage();
                      setState(() {});
                    }
                  },
                  child: Text("全屏观看"))
            ],
          )
        ],
      ),
    );
  }

  buildProgressSlider() {
    return GetBuilder(
      id: "progress",
      tag: widget.videoModel.id.toString(),
      builder: (VideoDetailsCodeLinkController controller) {
        bool loadingUserStudy = controller.loadingUserStudy;
        if (loadingUserStudy) {
          return LoadingWidget();
        }
        UserStudyCourseBean userStudyCourseBean =
            controller.userStudyCourseBean;
        if (userStudyCourseBean != null) {
          int studyFinish = userStudyCourseBean.studyFinish;
          if (studyFinish == 1) {
            return Container(
              padding: EdgeInsets.only(bottom: 20),
              child: Row(
                children: [
                  Image.asset(
                    "assets/images/2.0x/finish_icon.png",
                    width: 22,
                    height: 22,
                  ),
                  SizedBox(
                    width: 12,
                  ),
                  Text(
                    "已完成本视频的学习",
                    style: TextStyle(color: Colors.green),
                  )
                ],
              ),
            );
          }
        }
        return Container(
          padding: EdgeInsets.only(bottom: 20),
          child: Row(
            children: [
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: LinearProgressIndicator(
                  value: controller.getCurrentProgressValue(),
                  backgroundColor: Colors.grey,
                  valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Text(controller.getCurrentProgressStr()),
            ],
          ),
        );
      },
    );
  }

  FaiWebViewController faiWebViewController = new FaiWebViewController();

  void refreshHtmlPage() {
    Future.delayed(
        Duration(
          seconds: 1,
        ), () {
      ///向JS方法中传的参数
      Map<String, dynamic> map = new Map();
      map["test"] = "这是Flutter中传的参数33333";

      ///参数一为调用JS的方法名称
      ///参数二为向JS中传递的参数
      faiWebViewController.toJsFunction(
          jsMethodName: "updateVideoWidth", parameterMap: map);
    });
  }

  //当前点击的图片 URL
  String imageUrl;

  //是否显示浮动按钮
  bool isShowFloat = false;

  /**
   * code 当前点击图片的 位置
   * url 当前点击图片对应的 链接
   * images 当前 Html 页面中所有的图片集合
   */
  void imageCallBack(int code, String url, List<String> images) {
    imageUrl = url;
    setState(() {});
  }

  void callBack(int code, String msg, dynamic content) {
    if (code == 201) {
      //加载页面完成后 对页面重新测量的回调
      //这里没有使用到
      //当FaiWebViewWidget 被嵌套在可滑动的 widget 中，必须设置 FaiWebViewWidget 的高度
      //设置 FaiWebViewWidget 的高度 可通过在 FaiWebViewWidget 嵌套一层 Container 或者 SizeBox
      webViewHeight = content;
    } else if (code == 202) {
      // Html 页面中 Js 的回调
      // Html 页面中的开发需要使用 Js 调用
      // 【 Android 中 使用 controll.otherJsMethodCall( json )】
      // 【iOS中 直接调用 otherJsMethodCall( json ) 】
      // 在 Flutter 中解析 json 然后加载不同的功能
      String jsJson = content;
    } else if (code == 203) {
      // 为 Html 页面中的图片添加 点击事件后，点击图片会回调此方法
      // content 为当前点击图片的 地址
      // 实现更多功能 比如 一个 Html 页面中 有5张图片，点击放大查看并可右右滑动
      // 这个功能可以在 imageCallBack 回调中处理
    } else if (code == 301) {
      //当 WebView 滑动到顶部的回调
    } else if (code == 302) {
      //当 WebView 开始向下滑动时的回调
      //隐藏按钮
      isShowFloat = true;
    } else if (code == 303) {
      //当 WebView 开始向上滑动时的回调
      //显示按钮
      isShowFloat = false;
    } else if (code == 304) {
      //当 WebView 滑动到底部的回调
    } else if (code == 401) {
      //当 WebView 开始加载的回调
    } else if (code == 402) {
      //当 WebView 加载完成的回调
    } else if (code == 403) {
      // WebView 中 Html中日志输出回调
    } else if (code == 401) {
      // WebView 加载 Html 页面出错的回调
    } else if (code == 501) {
      // 当 Html 页面中有 Alert 弹框弹出时 回调消息
    } else if (code == 1000) {
      // 操作失败 例如 空指针异常 等等
    } else {
      //其他回调
    }
    setState(() {});
  }

  @override
  void dispose() {
    //不在使用
    Wakelock.disable();
    WidgetsBinding.instance.removeObserver(this);
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    _videoDetailsCodeLinkController.onClose();
    super.dispose();
    LogUtils.e("视频播放页面销毁");
  }
}
